require 'nokogiri'
require 'open-uri'

class MensaLoader

  Dish = Struct.new(:description, :price, :category, :tags)
  DAYS = %w(Montag Dienstag Mittwoch Donnerstag Freitag)

  def initialize(date)
    @date = date
  end

  def dishes
    result = DAYS.reduce({}) { |acc, day| acc[day] = []; acc }

    document.css("#week-menu tbody tr").each do |meal_by_type|
      category = meal_by_type.at_css('.category').content
      meal_by_type.css('.day').each_with_index do |day, index|
        if dish = day.at_css('.dish')
          result[DAYS[index]] << build_dish(dish, category)
        end
      end
    end

    result.sort_by { |day| DAYS.index(day.first) }.map(&:last)
  end

  def build_dish(dish, category)
    description = dish.css('strong').map(&:content).join.strip.gsub(/\([0-9]+(, [0-9]+)*\)/, "").gsub(/\s\s+/, " ")
    price = dish.css('.price').text
    tags = dish.css('img').map{ |e| e['title'] }

    Dish.new(description, price, category, tags)
  end

  def document
    Nokogiri::HTML(open(source_url))
  end

  def source_url
    "http://speiseplan.studwerk.uptrade.de/de/530/#{date.cwyear}/#{date.cweek}/".tap { |s| puts s }
  end

  private

  attr_reader :date

end
